package org.wuzhou.lvyou.map;

import org.wuzhou.lvyou.R;
import org.wuzhou.lvyou.activity.MainActivity;
import org.wuzhou.lvyou.base.BaseActivity;
import org.wuzhou.lvyou.util.GPSHelper;
import org.wuzhou.lvyou.util.MyLocation;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.NetworkInfo.State;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

public class WebMapActivity extends BaseActivity implements LocationListener {

	private static final String MAP_URL = "file:///android_asset/index.html";// "file:///android_asset/index.html"http://113.16.44.170:8080/wuzhoulvyou/test3.html
	private WebView webView;
	private Location mostRecentLocation = null;
	
	//private MyLocation myLocation=null;
	private LinearLayout webviewLayout = null;
	private WifiManager wifiManager = null;
	private Button btn_showScenicsplot;
	
	private Button btn_destance;
	private Button btn_dingwei;
	private Button btn_guide;
	private Button btn_search;
	private Button btn_near;
	private LinearLayout vebviewLayout;
	private GPSHelper mGps;
	private double latitude = 0;// 纬度；
	private double longitude = 0;// 经度
	private int scrH;// 屏幕高
	private int scrW;// 屏幕宽
	private int flags=0;
	private DisplayMetrics dm;

	private String _types[] = new String[] { "旅游景区", "旅馆酒店","餐馆小吃","ATM提款机","加油站" };

	@Override
	public void onCreate(Bundle savedInstanceState) {//
		super.onCreate(savedInstanceState);
		setContentView(R.layout.web_map);// 初始化界面
		dm = getResources().getDisplayMetrics();// 获取屏幕显示管理对象
		// 获取屏幕分辨率
		scrW = dm.widthPixels;
		scrH = dm.heightPixels;
		vebviewLayout = (LinearLayout) findViewById(R.id.webviewLayout);
		vebviewLayout.getLayoutParams().height = (int) scrH - 60;
		vebviewLayout.getLayoutParams().width = (int) scrW;
		Toast.makeText(getApplicationContext(), "宽度：" + scrW + "高度：" + scrH,
				Toast.LENGTH_LONG).show();
		//btn_showScenicsplot = (Button) findViewById(R.id.btn_showScenicsplot);
		btn_destance = (Button) findViewById(R.id.btn_destance);
		btn_dingwei = (Button) findViewById(R.id.btn_dingwei);
		btn_guide = (Button) findViewById(R.id.btn_guide);
		btn_search = (Button) findViewById(R.id.btn_search);
		btn_near = (Button) findViewById(R.id.btn_near);

		mGps = GPSHelper.getGpsInstance(getApplicationContext());
		mGps.openGps();
		setupWebView();
		setNetWork();
		this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

	}

	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {// 返回键
			_backToMain();
			//webView.goBack();
		}
		return false;
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		if(event.getAction()==MotionEvent.ACTION_MOVE){
			webView.goBack();
		}
		return true;
	}

	/**
	 * 网络设置
	 * 
	 */
	public void setNetWork() {
		wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
		if (!goodNet()) {
			new AlertDialog.Builder(this)
					.setTitle("开启网络连接？")
					.setMessage("网络尚未开启，请开启网络连接")
					.setPositiveButton("确定",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// TODO Auto-generated method stub
									Dialog dialog1 = new AlertDialog.Builder(
											WebMapActivity.this)
											.setTitle("开启网络连接？")
											.setMessage("请选择开启有效的网络连接")
											.setPositiveButton(
													"开启WIFI",
													new DialogInterface.OnClickListener() {

														@Override
														public void onClick(
																DialogInterface dialog,
																int which) {

															startActivity(new Intent(
																	android.provider.Settings.ACTION_WIFI_SETTINGS));

														}
													})
											.setNegativeButton(
													"开启GPRS",
													new DialogInterface.OnClickListener() {

														@Override
														public void onClick(
																DialogInterface dialog,
																int which) {
															// TODO
															// Auto-generated
															// method stub
															startActivity(new Intent(
																	android.provider.Settings.ACTION_WIRELESS_SETTINGS));
														}
													}).create();// 创建一个对话框
									dialog1.show();// 显示对话框
								}
							}).show();
		}
	}

	/**
	 * 检查网络是否已经打开
	 * @return
	 */
	public boolean goodNet() {
		ConnectivityManager manager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
		NetworkInfo networkinfo = manager.getActiveNetworkInfo();
		if (networkinfo == null || !networkinfo.isAvailable()) {
			return false;
		}
		return true;
	}

	/**
	 * 获取已经连接的网络类型3G或WIFI
	 * 
	 */
	private void checkNetworkInfo() {
		ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		State mobile = conMan.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
				.getState();
		new AlertDialog.Builder(this).setMessage(mobile.toString())
				.setPositiveButton("3G", null).show();// 显示3G网络连接状态
		State wifi = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
				.getState();
		new AlertDialog.Builder(this).setMessage(wifi.toString())
				.setPositiveButton("WIFI", null).show();// 显示wifi网络连接状态
	}

	/**
	 * 返回主界面
	 * 
	 */
	private void _backToMain() {
		Dialog dialog = new AlertDialog.Builder(WebMapActivity.this)
				.setTitle("返回主界面？")
				.setMessage("您确定要返回主界面吗？")
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						WebMapActivity.this.gotoActivity(WebMapActivity.this,
								MainActivity.class);
					}
				})
				.setNegativeButton("取消", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub

					}
				}).create();// 创建一个对话框
		dialog.show();// 显示对话框
	}

	/**
	 * 景点显示
	 * @param v
	 */
/*	
	public void showScenicSplot(View v) {
		if (btn_showScenicsplot.getText().equals("景点")) {
			btn_showScenicsplot.setText("隐藏");
			webView.loadUrl("javascript:setMarker()");
		} else if (btn_showScenicsplot.getText().equals("隐藏")) {
			btn_showScenicsplot.setText("景点");
			webView.loadUrl("javascript:hideMarker()");
		}
	}
*/
	/**
	 * 
	 * 附近搜索
	 * @param v
	 */

	public void showNearSpots(View v) {
		if (btn_near.getText().equals("旅游元素")) {
			btn_near.setText("隐藏元素");

			Dialog dialogtemp = new Builder(WebMapActivity.this)
			.setTitle("请选择搜索类型")
			.setNegativeButton("取消", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					
				}
			}).setItems(WebMapActivity.this._types, new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					switch(which){
					case 0:
						//旅游景区
						webView.loadUrl("javascript:showScenicPoints()");
						break;
						
					case 1:
						//旅馆酒店
						webView.loadUrl("javascript:showHotelPoints()");
						break;
						
					case 2:
						//餐馆小吃
						webView.loadUrl("javascript:showMealPoints()");
						break;
						
					case 3:
						//ATM提款机
						webView.loadUrl("javascript:showAtmPoints()");
						break;
						
					case 4:
						//加油站
						webView.loadUrl("javascript:showStationPoints()");
						break;
						
					}
					Toast.makeText(getApplicationContext(), which+"您选择的是： "+WebMapActivity.this._types[which], Toast.LENGTH_LONG).show();
				}
			}).create();
			dialogtemp.show();
		} else if (btn_near.getText().equals("隐藏元素")) {
			btn_near.setText("旅游元素");
			 webView.loadUrl("javascript:hideMarker()");
		}
	}

	/**
	 * 
	 * GPS定位
	 * @param v
	 */
	public void positionCheck(View v) {
		//mGps.openGps();
		if (btn_dingwei.getText().equals("定位")) {
			btn_dingwei.setText("取消");
			if (mGps.getmLatitude() == 0 && mGps.getmLongitude() == 0) {
				mGps.openGps();
				mGps.getmLatitude();
				mGps.getmLongitude();
				Toast.makeText(
						getApplicationContext(),
						mGps.getmLatitude() + "    >>>   "
								+ mGps.getmLongitude(), Toast.LENGTH_LONG)
						.show();

			}
			String jsStr = "javascript:showCurrentPosition("
					+ mGps.getmLatitude() + "," + mGps.getmLongitude() + ")";
			webView.loadUrl(jsStr);

		} else if (btn_dingwei.getText().equals("取消")) {
			btn_dingwei.setText("定位");
			webView.loadUrl("javascript:hideCurrentPosition()");
		}

	}

	/**
	 * 
	 * 测距
	 * @param v
	 */
	public void destance(View v) {
		if (btn_destance.getText().equals("测距")) {
			btn_destance.setText("取消");
			webView.loadUrl("javascript:getDistance()");
		} else if (btn_destance.getText().equals("取消")) {
			btn_destance.setText("测距");
			webView.loadUrl("javascript:clearLis()");
		}
	}

	/**
	 * 
	 * 路线搜索
	 * @param v
	 */
	public void guide(View v) {
		if (btn_guide.getText().equals("路线")) {
			btn_guide.setText("取消");
			webView.loadUrl("javascript:addPoint()");
		} else if (btn_guide.getText().equals("取消")) {
			btn_guide.setText("路线");
			webView.loadUrl("javascript:clearPath()");
		}
	}

	/**
	 * 
	 * 地点搜索
	 * @param v
	 */
	public void search(View v) {
		if (btn_search.getText().equals("搜索")) {
			btn_search.setText("取消");
			webView.loadUrl("javascript:showSearch()");// /showSearch()
		} else if (btn_search.getText().equals("取消")) {
			btn_search.setText("搜索");
			webView.loadUrl("javascript:hideSearch()");
		}
	}


	/** 初始化地图界面 **/
	private void setupWebView() {
		openGPSSettings();
		final String divSize = "javascript:setMapDiv(" + scrW + ","
				+ (scrH - 50) + ")";
		webviewLayout = (LinearLayout) findViewById(R.id.webviewLayout);
		webView = (WebView) findViewById(R.id.webview);

		webView.getSettings().setJavaScriptEnabled(true);
		webView.addJavascriptInterface(new JavaScriptInterface(), "Android");
		// 装载web网页并设置地图适应手机屏幕的大小
		webView.setWebViewClient(new WebViewClient() {
			@Override
			public void onPageFinished(WebView view, String url) {
				webView.loadUrl(divSize);
			}
			//调用外部浏览器
			
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url)         {                            //重写方法
				Uri uri = Uri.parse(url); //url为你要链接的地址
	              Intent intent =new Intent(Intent.ACTION_VIEW, uri);
	              startActivity(intent);
	              return true;
	        }
//			@Override
//			public boolean shouldOverrideUrlLoading(WebView view, String url){//重写方法
//				if(flags==0){
//					flags=1;
//					return false;
//				}
//				if(flags==1){
//				Uri uri = Uri.parse(url); //url为你要链接的地址
//	              Intent intent =new Intent(Intent.ACTION_VIEW, uri);
//	              startActivity(intent);
//	              return true;
//				}
//				return true;
//	        }
		});
		webView.loadUrl(MAP_URL);

	}

	/**
	 * 
	 * 判断GPS 是否开启
	 */
	private void openGPSSettings() {
		LocationManager alm = (LocationManager) this
				.getSystemService(Context.LOCATION_SERVICE);
		if (!alm.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
			Toast.makeText(this, "请开启GPS！", Toast.LENGTH_SHORT).show();
			Dialog dialog = new AlertDialog.Builder(WebMapActivity.this)
			.setTitle("提示")
			.setMessage("本系统需要开启GPS功能，是否开启？")
			.setPositiveButton("确定", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
					startActivityForResult(intent, 0); // 此为设置完成后返回到获取界面
				}
			})
			.setNegativeButton("取消", new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub

				}
			}).create();// 创建一个对话框
			dialog.show();// 显示对话框
			// Intent intent = new Intent(Settings.ACTION_SECURITY_SETTINGS);

		} else {
			getLocation();

		}
	}

	/**
	 * 
	 * GPS获取地理信息
	 */
	private void getLocation() {
		// 获取位置管理服务
		LocationManager locationManager;
		String serviceName = Context.LOCATION_SERVICE;
		locationManager = (LocationManager) this.getSystemService(serviceName);
		// 查找到服务信息
		Criteria criteria = new Criteria();
		criteria.setAccuracy(Criteria.ACCURACY_FINE); // 高精度

		criteria.setAltitudeRequired(false);
		criteria.setBearingRequired(false);
		criteria.setCostAllowed(true);
		criteria.setPowerRequirement(Criteria.POWER_LOW); // 低功耗

		String provider = locationManager.getBestProvider(criteria, true); // 获取GPS信息
		Location location = locationManager.getLastKnownLocation(provider); // 通过GPS获取位置
		locationManager.requestLocationUpdates(provider, 1, 0, this);

	}

	@Override
	public void onLocationChanged(Location location) {
		mostRecentLocation = location;
	}

	@Override
	public void onProviderDisabled(String provider) {

	}

	@Override
	public void onProviderEnabled(String provider) {

	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {

	}

	/**
	 * 支持页面调用的类
	 * 
	 **/
	private class JavaScriptInterface {

		public double getLatitude() {
			return mostRecentLocation.getLatitude();
		}

		public double getLongitude() {
			return mostRecentLocation.getLongitude();
		}

		/** 获取页面数据信息 */
		public void showToast(String toast) {
			Toast.makeText(getApplicationContext(), toast, Toast.LENGTH_SHORT)
					.show();
		}
		
		public void phoneCall(String str){
			
			Intent intent=new Intent();
			
			intent.setAction("android.intent.action.CALL");
			
			intent.setData(Uri.parse("tel:"+str));
			
			startActivity(intent);
		}
	}

}
